package com.atguigu.gulimall.auth.controller;


import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.service.LoginService;
import com.atguigu.gulimall.auth.vo.RegisterUserVo;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/11
 * @Version 1.0
 */
@Controller
public class LoginController {
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 前端请求该接口，用于调用第三方服务发送验证码
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone")String phone){
        //TODO 1、接口防刷
        //2、保证严格用意义上的60秒,验证码后加上系统时间
        String cacheCode = stringRedisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(cacheCode)){
            long oldTime = Long.parseLong(cacheCode.split("_")[1]);
            if(System.currentTimeMillis()-oldTime < 60000){
                //发送验证码间隔小于60秒
                return R.error(BizCodeEnume.SMS_CODE_EXISTS.getCode(),BizCodeEnume.SMS_CODE_EXISTS.getMsg());
            }
        }
        String code=UUID.randomUUID().toString().substring(0, 6);
         String codeAndTime = code+"_"+System.currentTimeMillis();
        //向存储验证码，十分钟有效
        stringRedisTemplate.opsForValue().set(AuthServiceConstant.SMS_CODE_CACHE_PREFIX+phone,codeAndTime,10, TimeUnit.MINUTES);
        //向第三方服务发送验证码
        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * 用户注册，前端会先请求这个地址
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid RegisterUserVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            //Duplicate key 添加重复的可key是要加上最后的一步，即错误信息叠加(s, a) -> s + a),也可以替换，如(s, a) -> a )
            Map<String, String> errMsg = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage,(s, a) -> a ));
            //请求转发，请求转发必须使用get请求，由于我们注册方法是post请求，所以这里不能使用请求转发
//            return "forword:/register.html";
            //跳转到register.html，这种方式刷新浏览器时会重复提交表单，为了避免重复表单数据提交，可以使用重定向
//            model.addAttribute("errors",errMsg);
            //向重定向对象添加一次性的数据，下次刷新页面时数据就会消失
            redirectAttributes.addFlashAttribute("errors",errMsg);
            return "redirect:http://auth.gulimall.com/register.html";
        }
        //验证通过，则进行注册，远程调用会员服务进行用户注册
        //1、校验验证码
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
            //s.split("_")[0])，截取出真正的验证码
            if(code.equals(s.split("_")[0])){
                //1、验证通过,删除验证码
                stringRedisTemplate.delete(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //2、远程调用会员服务
                R register = memberFeignService.register(vo);
                if(register.getCode() ==0){
                    //远程调用成功，跳转到登录页
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    //获取失败信息
                    Map<String,String> erroeMap=new HashMap<>();
                    String errMsg = register.getData("msg",new TypeReference<String>() {
                    });
                    erroeMap.put("msg",errMsg);
                    redirectAttributes.addFlashAttribute("errors",errMsg);
                    //跳转到注册页面
                    return "redirect:http://auth.gulimall.com/register.html";
                }
            }else {
                //验证码不一致
                Map<String, String> errors=new HashMap<>();
                errors.put("code","验证码错误");
                //校验错误，跳转到注册页面
                return "redirect:http://auth.gulimall.com/register.html";
            }
        }else {
            //验证码为空，则验证码错误
            Map<String, String> errors=new HashMap<>();
            errors.put("code","验证码错误");
            //校验错误，跳转到注册页面
            return "redirect:http://auth.gulimall.com/register.html";
        }
    }

    /**
     * 用户登录
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程调用会员服务
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0){
            //登录成功，返回首页
            MemberVo data = login.getData("data", new TypeReference<MemberVo>() {
            });
            //向session存储数据
            session.setAttribute(AuthServiceConstant.SESSION_USER_NAME,data);
            return "redirect:http://gulimall.com";
        }else {
            Map<String,String > msgMap=new HashMap<>();
            msgMap.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors",msgMap);
            //登录失败，返回登录页面
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

    /**
     * 登录页的处理请求，若用户登录过，访问登录页面时也跳转到首页
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServiceConstant.SESSION_USER_NAME);
        if(attribute == null){
            //未登陆过，跳转到登录页
            return "login";
        }else {
            //登录过，直接跳转到首页
            return "redirect:http://gulimall.com";
        }
    }
}
